//
//  KSInboundDiffViewController.swift
//  Supermarket
//
//  Created by liuxm on 2017/9/28.
//  Copyright © 2017年 kushao. All rights reserved.
//

import UIKit
import MJRefresh

/// 验收差异
class KSInboundDiffViewController: KSBaseViewController,KSCompleteEventDelegate,UISearchBarDelegate {
    
    @IBOutlet weak var dateBtn: UIButton!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var searchBar: UISearchBar!
    private var diffDataArray: [KSInboundDiffDataListModel] = []
    private var timeView: KSChooseTimeView!
    private var searchBarTxt = ""
    private var startTime = ""
    private var endTime = ""
    private var page = 1
    
    private lazy var notHaveDataExistView: KSNotHaveDataExistView = {
        let view = KSNotHaveDataExistView(frame: self.view.bounds)
        view.initView(imageName: "Common_CollectionEmpty", content: "暂无验收差异")

        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        self.title = "验收差异"
        dateBtn.setIconInRightWithSpacing(spacing: 2)
        
        searchBar.delegate = self
        
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.backgroundColor = UIColor.colorWithHexString(hex: "#f3f6f7")
        
        let nib = UINib(nibName: "KSInboundDiffTableViewCell", bundle: nil)
        self.tableView.register(nib, forCellReuseIdentifier: "KSInboundDiffTableViewCell")
        tableView.mj_header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(loadNewData))
        tableView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingTarget: self, refreshingAction: #selector(loadMoreData))
        tableView.mj_footer.isHidden = true
        tableView.estimatedRowHeight = 131
        
        timeView = KSChooseTimeView(frame: CGRect.init(x: 0, y: 0, width: KSConstants.kScreenWidth, height: KSConstants.kScreenHeight))
        timeView.isHidden = true
        timeView.delegate = self
        self.view.addSubview(timeView)
        
        self.startLoading()
        self.requestData()
    }
    
    override func requestSuccess(result: String, apiType: KSApiType) {
        super.requestSuccess(result: result, apiType: apiType)
        
        let inboundDiffModel = KSInboundDiffModel.deserialize(from: result)
        let diffList = inboundDiffModel?.data?.list
        
        if diffList!.count > 0 {
            if self.page == 1 {
                diffDataArray.removeAll()
            }
            diffDataArray = diffDataArray + diffList!
        } else {
            if self.page > 1 {
                self.page -= 1
            }
        }
        
        tableView.reloadData()
        tableView.mj_header.endRefreshing()
        tableView.mj_footer.endRefreshing()
        
        if diffDataArray.count == 0 {
            self.view.addSubview(self.notHaveDataExistView)
        }
    }
    
    override func requestFaile(code: Int, message: String, apiType: KSApiType) {
        super.requestFaile(code: code, message: message, apiType: apiType)
        
        if self.page > 1 {
            self.page -= 1
        }
    }
    
    @objc func loadNewData() {
        self.page = 1
        self.requestData()
    }
    
    @objc func loadMoreData() {
        if !(tableView.mj_header.state == MJRefreshState.refreshing) {
            self.page += 1
            self.requestData()
        }
    }
    
    private func requestData() {
        let parameter = ["page" : "1","order_number" : self.searchBarTxt, "storage_name" : "","merchant_name" : "","start_date" : self.startTime,"end_date" : self.endTime]
        self.request.requestStorageOrderDiffList(parameters: parameter)
    }
    
    func completeClick(startTime: String, endTime: String) {
        self.startTime = startTime
        self.endTime = endTime
        self.requestData()
    }
    
    func cancleClick() {
        
    }
    
    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
        self.searchBarTxt = searchBar.text!
        self.requestData()
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        self.searchBarTxt = searchBar.text!
        self.requestData()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func dateBtnClick(_ sender: Any) {
        timeView.isHidden = false
    }
}

extension KSInboundDiffViewController: UITableViewDelegate, UITableViewDataSource {
    
    // UITableViewDataSource
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return diffDataArray.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    // UITableViewDelegate
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 131
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "KSInboundDiffTableViewCell", for: indexPath) as! KSInboundDiffTableViewCell
        cell.setDataWithModel(model: diffDataArray[indexPath.row])
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = diffDataArray[indexPath.row]
        let vc = KSInboundDiffDetailViewController()
        vc.orderNumber = model.order_number
        self.navigationController?.pushViewController(vc, animated: true)
    }
}
